package pt.isel.pdm.ouryamba;

import java.util.List;
import winterwell.jtwitter.Twitter;
import android.app.IntentService;
import android.content.Intent;
import android.os.IBinder;

public class TimelinePullService extends IntentService
{

	private General app;
	public static final String ID = "TimelinePullService";
	private static final String WORKER_THREAD_NAME = ID + "_worker_thread";

	
//Service methods
	
	public TimelinePullService() 
	{
		super(WORKER_THREAD_NAME);
	}
	
	/**
	 * Since this is a started service, the is no object to bind.
	 * */
	@Override
	public IBinder onBind(Intent arg0)
	{
		return null;
	}

	/**
	 * Starts the background worker thread and initialize some variables.
	 * */
	@Override
	public void onCreate() 
	{
		super.onCreate();
		app = (General) getApplication();
	}
	
	/**
	 * Stops the background worker thread and reference it to null (helps the GC), only if
	 * there is none network connectivity and the automatic updates are not enabled.
	 * */
	@Override
	public void onDestroy()
	{
		super.onDestroy();
	}

	/**
	 * Fetches the list of statuses through the worker thread.</br>
	 * 
	 * Uses the block mechanism from the {@code queue} variable to wait for work.
	 * Notify all waiters when the update is accomplished or when there are requests and the is no
	 * connectivity network. </br>
	 * 
	 * After fetching the list of new status from the server, remove all the status from the database
	 * with committed value true, and insert the new list.
	 * Also notifies that the list was updated so the notification system can do his work (show or not
	 * the notification in the notification bar).
	 * 
	 * @see General#hasNetworkConnection()
	 * @see General#log(String)
	 * @see Waiter#NotifyAll()
	 * @see General#getTwitter()
	 * @see General#dbDeleteByCommitedValue(boolean)
	 * @see General#dbInsertMany(List<Status>, boolean)
	 * @see General#timelineUpdated(long)
	 * @see General#logException(Exception)
	 * */
	@Override
	protected void onHandleIntent(Intent intent)
	{
		app.log(ID + ".onHandleIntent(): Request received.");
		try
		{
			if(!app.hasNetworkConnection())
			{
				app.log(ID + ".onHandleIntent(): Updates discarded because network unavailable.");
				app.waiter.NotifyAll();
				return;
			}
			List<Twitter.Status> list = app.getTwitter().getUserTimeline();
			app.log(ID + ".onHandleIntent(): Timeline fetched.");
			app.dbDeleteByCommitedValue(true);
			app.dbInsertMany(list, true);
			if(list.size() > 0)
			{
				app.timelineUpdated(list.get(0).id);
			}
			app.waiter.NotifyAll();
		}
		catch (Exception e)
		{
			app.log(ID + ".onHandleIntent(): Exception thrown.");
			app.logException(e);
		}
	}

}
 